#!/usr/bin/env python3

# Copyright (c) 2020-2021 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

import re
import pathlib


def is_arch_and_windows_version_match(wine_arch, wine_windows_version):
    return wine_windows_version in _archWindowsVersionDict[wine_arch]


def filter_windows_versions_by_arch(wine_arch, wine_windows_versions):
    ret = []
    for x in _archWindowsVersionDict[wine_arch]:
        if x in wine_windows_versions:
            ret.append(x)
    return ret


class WindowsRegistryText:

    def __init__(self):
        self._keyDict = dict()

    def is_empty(self):
        return len(self._keyDict) == 0

    def add_key(self, key):
        if key not in self._keyDict:
            self._keyDict[key] = {}

    def add_value(self, key, value_name, value_type, data):
        assert self._check_value_type(value_type)
        if key not in self._keyDict:
            self._keyDict[key] = {}
        self._keyDict[key][value_name] = (value_type, data)

    def get_text(self):
        buf = ""
        for key, v in self._keyDict.items():
            buf += f"[{key}]\n"
            for value_name, (value_type, data) in v.items():
                if value_name == "@":
                    value_name = ""
                else:
                    value_name = f'"{value_name}"'
                buf += "%s=%s\n" % (value_name, self._format_data(value_type, data))
            buf += "\n"
        return buf

    def __str__(self):
        return self.get_text()

    def _check_value_type(self, value_type):
        if value_type == "REG_SZ" or value_type == "REG_EXPAND_SZ":
            return True
        if value_type == "REG_DWORD":
            return True
        if value_type == "REG_BINARY":
            return True
        if value_type == "REG_MULTI_SZ":
            return True
        return False

    def _format_data(self, value_type, data):
        if value_type == "REG_SZ" or value_type == "REG_EXPAND_SZ":
            return f'"{data}"'

        if value_type == "REG_DWORD":
            return f"dword:{data:08x}"

        if value_type == "REG_BINARY":
            assert isinstance(data, bytes)
            return "hex:" + ",".join(f"{b:02x}" for b in data)

        if value_type == "REG_MULTI_SZ":
            assert isinstance(data, list) and all(isinstance(item, str) for item in data)
            return "hex(7):" + ",".join(",".join(f"{ord(c):02x}" for c in item + "\0") for item in data) + ",00,00"

        assert False


class WindowsRegistryFileReader:

    def __init__(self, path):
        self._path = path
        self._text = pathlib.Path(self._path).read_text(encoding="utf-16-le").replace("\r\n", "\n")

    def get_text(self):
        return self._text


class WindowsRegistryFileWriter:

    def __init__(self, path=None):
        self._path = path
        self._textOrStrList = []

    def is_empty(self):
        return len(self._textOrStrList) == 0

    def add_key(self, key):
        if len(self._textOrStrList) == 0 or not isinstance(self._textOrStrList[-1], WindowsRegistryText):
            self._textOrStrList.append(WindowsRegistryText())
        self._textOrStrList[-1].add_key(key)

    def add_value(self, key, value_name, value_type, data):
        if len(self._textOrStrList) == 0 or not isinstance(self._textOrStrList[-1], WindowsRegistryText):
            self._textOrStrList.append(WindowsRegistryText())
        self._textOrStrList[-1].add_value(key, value_name, value_type, data)

    def add_text(self, text):
        assert not isinstance(text, WindowsRegistryText)

        # remove heading
        text = re.sub('^Windows Registry Editor Version 5\\.00\n', '', text)
        text = text.lstrip("\n")

        self._textOrStrList.append(text)

    def save(self, path=None):
        if path is not None:
            self._path = path

        with open(self._path, "wb") as f:
            f.write(b'\xFF\xFE')
            f.write("Windows Registry Editor Version 5.00\r\n".encode("utf-16-le"))     # this heading is neccessary, sucks
            f.write("\r\n".encode("utf-16-le"))
            for item in self._textOrStrList:
                f.write(str(item).replace("\n", "\r\n").encode("utf-16-le"))
                f.write("\r\n".encode("utf-16-le"))


_archWindowsVersionDict = {
    "win32": [
        "win95",
        "win98",
        "winxp",
    ],
    "win64": [
        "winxp64",
        "win2008",
        "win2008r2",
        "win7",
        "win8",
        "win81",
        "win10",
        "win11",
    ],
}
